/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/

#include "main.h"
#include "adc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

#include <string.h>
#include "sht30.h"
#include "bc28.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

#define  DBG_PRINT
#ifdef 	 DBG_PRINT
#define dbg_printf(format,args...) printf(format, ##args)
#else
#define dbg_printf(format,args...) do{} while(0)
#endif

#define	SEND_INTERVAL	 30000								/* Sending interval time */
#define	FR_BAND			"AT+NBAND=5,8\r\n"					/* Frequency band of BC28 module */
#define	PLATFORM		"AT+NCDP=221.229.214.202,5683\r\n"	/* The BC28 module is connected to the cloud platform */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* Send temperature and humidity to cloud platform function */
int report_temp_and_humi(void);

/* Send light strength to cloud platform function */
int	report_lux(void);

/* Send soil humidity to cloud platform function */
int report_soil_humidity(void);

/* Send signal strength to cloud platform function */
int report_signal(void);


/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

	uint32_t			latest_time;		/* to save the latest time */
	int					rv = -1;			/* to save the return values*/

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_USART3_UART_Init();
  MX_TIM6_Init();
  MX_ADC1_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

  printf("The program start to run ...\r\n");
  sysled_heardbeat();

  /* The program starts to  sampling 10 seconds after running */
  latest_time = ((HAL_GetTick()+(int)SEND_INTERVAL)-10);

Reset:

  fail_beat();		/* Failure indicator light */

  if( (rv = nb_iot_module_init(FR_BAND) ) != 0)
  {
	  printf("NB-IoT module initial failure\r\n");
	  printf("rv = %d \r\n", rv);
	  HAL_Delay(500);
	  goto Reset;
  }

  dbg_printf("NB-IoT module initial successfully\r\n");
  success_beat();	/* Success indicator light */

  if( (rv = nb_iot_connect(PLATFORM) ) != 0)
  {
	  printf("NB-IoT connect failure\r\n");
	  dbg_printf("rv = %d \r\n", rv);
	  HAL_Delay(500);
	  goto Reset;
  }

  dbg_printf("NB-IoT connect successfully\r\n");
  success_beat();

  while (1)
  {
	  /* Parse the received data and process it */
	  if ( parse_recv_cmd(g_atcmd_rxbuf) )
	  {
		  printf("ERROR:parse_recv_cmd input cmd invalid\r\n");
		  continue;
	  }

	  /* Serial port forwarding function for debugging */
	  uart_forward();

	  /* Use the time_afert macro to solve the problem of time winding and call delay wasting CUP */
	  if(time_after(HAL_GetTick(),latest_time+SEND_INTERVAL))
	  {
		  /* Send the temperature and humidity to the cloud platform */
		  rv = report_temp_and_humi();

		  if( -1==rv )
		  {
			  printf("SHT30_SampleData failure and retry now!\r\n");
			  HAL_Delay(1000);
			  continue;
		  }

		  else if( -2==rv )
		  {
			  printf("Send temperature and humidity to cloud failure and reset NB-IoT now!\r\n");
			  goto Reset;
		  }

		  dbg_printf("Send temperature and humidity to cloud successfully!\r\n");
		  success_beat();

		  /* Send the light strength to the cloud platform */
		  rv = report_lux();

		  if( -1==rv )
		  {
			  printf("Sample light strength  failure and retry now!\r\n");
			  HAL_Delay(1000);
			  continue;
		  }

		  else if( -2==rv )
		  {
			  printf("Send Lux to cloud failure and reset NB-IoT now!\r\n");
			  goto Reset;
		  }

		  dbg_printf("Get Lux strength successfully! \r\n");
		  success_beat();

		  /* Send the soil humidity to the cloud platform */
		  rv = report_soil_humidity();

		  if( -1==rv )
		  {
			  printf("Sample soil humidity  failure and retry now!\r\n");
			  HAL_Delay(1000);
			  continue;
		  }

		  else if( -2==rv )
		  {
			  printf("Send soil humidity to cloud failure and reset NB-IoT now!\r\n");
			  goto Reset;
		  }

		  dbg_printf("Get soil humidity successfully! \r\n");
		  success_beat();

		  /* Send the signal strength to the cloud platform */
		  rv = report_signal();

		  if( -1==rv )
		  {
			  printf("Sample signal strength failure and retry now!\r\n");
			  HAL_Delay(1000);
			  continue;
		  }

		  else if( -2==rv )
		  {
			  printf("Send signal strength to cloud failure and reset NB-IoT now!\r\n");
			  goto Reset;
		  }

		  dbg_printf("Send signal strength to cloud successfully!\r\n");
		  success_beat();

		  latest_time = HAL_GetTick();
		  HAL_Delay(100);

	  }

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */

  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 1;
  RCC_OscInitStruct.PLL.PLLN = 20;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_USART3
                              |RCC_PERIPHCLK_ADC;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
  PeriphClkInit.Usart3ClockSelection = RCC_USART3CLKSOURCE_PCLK1;
  PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_PLLSAI1;
  PeriphClkInit.PLLSAI1.PLLSAI1Source = RCC_PLLSOURCE_HSE;
  PeriphClkInit.PLLSAI1.PLLSAI1M = 1;
  PeriphClkInit.PLLSAI1.PLLSAI1N = 9;
  PeriphClkInit.PLLSAI1.PLLSAI1P = RCC_PLLP_DIV7;
  PeriphClkInit.PLLSAI1.PLLSAI1Q = RCC_PLLQ_DIV2;
  PeriphClkInit.PLLSAI1.PLLSAI1R = RCC_PLLR_DIV6;
  PeriphClkInit.PLLSAI1.PLLSAI1ClockOut = RCC_PLLSAI1_ADC1CLK;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

int report_temp_and_humi(void)
{
	float	temperature, humidity;

	/* Get temperature and humidity */
	if ( SHT30_SampleData(&temperature,&humidity ) !=0 )
	{
		dbg_printf("SHT30_SampleData failure and retry now!\r\n");
		return -1;
	}

	dbg_printf("Get temperature and humidity successfully! \r\n\r\n Current temperature:%.2f \
				Current humidity:%.2f\r\n", temperature, humidity);

	/* Send temperature and humidity */
	if( nb_iot_send_TH(temperature,humidity ) != 0)
	{
		dbg_printf("nb_iot_send_msg failure and reset now!\r\n");
		return -2;
	}

	dbg_printf("Send TH to cloud successfully\r\n");
	return 0;

}

int	report_lux(void)
{
	uint32_t			lux;

	/* Get light strength */
	if( adc_sample_lux(&lux) )
	{
		dbg_printf("ERROR:Get light strength fail! \r\n");
		return -1;

	}

	dbg_printf("Get light strength successfully! \r\n\r\n Current Lux strength :%ld\r\n\r\n", lux);

	/* Send light strength*/
	if( nb_iot_send_lux(lux) )
	{
		dbg_printf("ERROR:nb_iot_send_lux call fail and reset now!\r\n");
		return -2;

	}

	dbg_printf("Send light strength to cloud successfully\r\n");
	return 0;
}

int	report_soil_humidity(void)
{
	uint32_t			humidity;

	/* Get soil humidity */
	if( adc_sample_soil_humidity(&humidity) )
	{
		dbg_printf("ERROR:Get soil humidity fail! \r\n");
		return -1;

	}

	dbg_printf("Get soil humidity successfully! \r\n\r\n Current soil humidity :%ld\r\n\r\n", humidity);

	/* Send soil humidity */
	if( nb_iot_send_soil_humidity(humidity) )
	{
		dbg_printf("ERROR:nb_iot_send_soil_humidity call fail and reset now!\r\n");
		return -2;

	}

	dbg_printf("Send soil humidity to cloud successfully\r\n");
	return 0;
}

int report_signal(void)
{
	  int	signal;

	  /* Get signal strength */
	  if( (signal = nb_iot_get_sign()) < 0)
	  {
		  dbg_printf("ERROR:nb_iot_get_sign call fail\r\n");
		  return -1;
	  }

	  dbg_printf("Get signal strength successfully! \r\n\r\n Current signal strength:%d\r\n\r\n", signal);

	  /* Send signal strength */
	  if( nb_iot_send_sign(signal) )
	  {
		  dbg_printf("ERROR:nb_iot_send_sign call fail and reset now!\r\n");
		  return -2;;

	  }

	  dbg_printf("Send signal strength to cloud successfully\r\n");
	  return 0;
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
